<script setup>
import { ref, onMounted } from 'vue';
import { List, Cell, Button, showDialog, Search, DatePicker, Popup, Field, DropdownMenu, DropdownItem } from 'vant';
import { getTaskInstancePage, getTaskLog, getTaskLogTail } from '@/api/dolphin';
import { useRoute } from 'vue-router';

const route = useRoute();
const loading = ref(false);
const finished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);
const items = ref([]);
const value = ref('');
const clusterId = ref(route.params.clusterId);
const projectCode = ref(Number(route.params.projectCode));
const processInstanceId = ref(route.params.processInstanceId);
const processInstanceName = ref(
  route.params.processInstanceName ? decodeURIComponent(route.params.processInstanceName) : ''
);

// 添加状态和日期相关的 ref
const stateType = ref('');
const startDate = ref('');
const endDate = ref('');

// 添加状态选项
const stateOptions = [
  { text: '全部', value: '' },
  { text: '提交成功', value: 'SUBMITTED_SUCCESS' },
  { text: '运行中', value: 'RUNNING_EXECUTION' },
  { text: '准备暂停', value: 'READY_PAUSE' },
  { text: '暂停', value: 'PAUSE' },
  { text: '准备停止', value: 'READY_STOP' },
  { text: '停止', value: 'STOP' },
  { text: '失败', value: 'FAILURE' },
  { text: '成功', value: 'SUCCESS' },
  { text: '需要容错', value: 'NEED_FAULT_TOLERANCE' },
  { text: '终止', value: 'KILL' }
];

// 获取状态显示文本
const getStateText = (value) => {
  const option = stateOptions.find(opt => opt.value === value);
  return option ? option.text : '全部';
};

// 重置搜索条件
const onReset = () => {
  value.value = '';
  stateType.value = '';
  startDate.value = '';
  endDate.value = '';
  onSearch();
};

const onLoad = async () => {
  try {
    loading.value = true;
    const response = await getTaskInstancePage(
      clusterId.value,
      projectCode.value,
      currentPage.value,
      pageSize.value,
      processInstanceId.value,
      value.value,
      stateType.value,
      startDate.value,
      endDate.value
    );
    
    let records = response.records || [];
    
    // 按照 id 升序排序（按执行顺序）
    records.sort((a, b) => a.id - b.id);
    
    if (currentPage.value === 1) {
      items.value = records;
    } else {
      items.value.push(...records);
    }
    
    totalItems.value = response.totalCount;

    if (records.length < pageSize.value || items.value.length >= totalItems.value) {
      finished.value = true;
    } else {
      currentPage.value++;
    }
  } catch (error) {
    console.error('加载任务实例失败:', error);
    finished.value = true;
  } finally {
    loading.value = false;
  }
};

const viewTaskLogTail = async (taskInstanceId) => {
  try {
    const log = await getTaskLogTail(
      clusterId.value,
      projectCode.value,
      taskInstanceId,
      100
    );
    showDialog({
      title: '任务日志',
      message: log || '暂无日志',
      confirmButtonText: '确定',
      className: 'task-log-dialog',
      messageAlign: 'left'
    });
  } catch (error) {
    console.error('获取日志失败:', error);
  }
};

const onSearch = () => {
  currentPage.value = 1;
  items.value = [];
  finished.value = false;
  loading.value = false;
  onLoad();
};

// 添加初始化加载
onMounted(() => {
  onSearch();
});

// 添加状态显示相关方法
const getStateClass = (state) => {
  // 运行相关状态
  if (['RUNNING_EXECUTION', 'SUBMITTED_SUCCESS'].includes(state)) {
    return 'state-running';
  }
  // 成功状态
  if (state === 'SUCCESS') {
    return 'state-success';
  }
  // 失败相关状态
  if (['FAILURE', 'NEED_FAULT_TOLERANCE'].includes(state)) {
    return 'state-failed';
  }
  // 暂停相关状态
  if (['PAUSE', 'READY_PAUSE'].includes(state)) {
    return 'state-paused';
  }
  // 停止相关状态
  if (['STOP', 'READY_STOP', 'KILL'].includes(state)) {
    return 'state-stopped';
  }
  // 其他状态
  return 'state-default';
};
</script>

<template>
  <div class="page-container">
    <div class="header">
      <h2 class="title">工作流任务列表</h2>
      <div class="workflow-info" v-if="processInstanceName">
        <span class="label">工作流实例：</span>
        <span class="value">{{ processInstanceName }}</span>
      </div>

      <!-- 搜索区域 -->
      <div class="search-content">
        <!-- 搜索输入框 -->
        <div class="search-item">
          <van-search
            v-model="value"
            placeholder="搜索任务名称"
            shape="round"
            background="#f7f8fa"
            @search="onSearch"
          />
        </div>

        <!-- 状态选择 -->
        <div class="search-item">
          <van-dropdown-menu class="status-dropdown">
            <van-dropdown-item
              v-model="stateType"
              :options="stateOptions"
            >
              <template #title>
                <span>状态: {{ getStateText(stateType) }}</span>
              </template>
            </van-dropdown-item>
          </van-dropdown-menu>
        </div>

        <!-- 时间输入 -->
        <div class="search-item">
          <van-field
            v-model="startDate"
            label="开始日期"
            placeholder="YYYY-MM-DD"
            input-align="left"
          />
        </div>
        <div class="search-item">
          <van-field
            v-model="endDate"
            label="结束日期"
            placeholder="YYYY-MM-DD"
            input-align="left"
          />
        </div>

        <!-- 按钮组 -->
        <div class="button-group">
          <van-button type="primary" size="small" @click="onSearch">搜索</van-button>
          <van-button type="primary" size="small" @click="onReset">重置</van-button>
        </div>
      </div>
    </div>
    
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多数据了"
      @load="onLoad"
      class="task-list"
    >
      <van-cell
        v-for="(item, index) in items"
        :key="index"
        :title="item.name"
        class="task-item"
      >
        <template #label>
          <span class="task-info">
            <span class="task-id">ID: {{item.id}}</span>
            <span :class="['task-state', getStateClass(item.state)]">
              {{ getStateText(item.state) }}
            </span>
            <span class="task-time">{{new Date(item.startTime).toLocaleString()}}</span>
          </span>
        </template>
        <template #right-icon>
          <div class="action-buttons">
            <van-button
              round
              type="success"
              size="small"
              icon="passed"
              name="task-status"
              class="status-btn"
            ></van-button>
            <van-button 
              round 
              type="primary" 
              size="small" 
              icon="description-o"
              name="view-task-log"
              title="查看任务日志"
              class="log-btn"
              @click.stop="viewTaskLogTail(item.id)"
            ></van-button>
          </div>
        </template>
      </van-cell>
    </van-list>
  </div>
</template>

<style scoped>
/* 添加搜索区域样式 */
.search-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 12px;
  background: #fff;
}

.search-item {
  width: 100%;
}

.status-dropdown {
  width: 100%;
}

:deep(.van-dropdown-menu) {
  height: 36px;
  background: var(--van-field-background);
  border-radius: 2px;
}

:deep(.van-dropdown-menu__bar) {
  box-shadow: none;
  height: 36px;
}

.button-group {
  grid-column: span 2;
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 8px;
}

/* 调整列表容器高度，为搜索区域留出空间 */
.list-container {
  height: calc(100vh - 280px);
}

/* 保持原有样式 */
.page-container .header {
  margin-bottom: 16px;
}

.page-container .header .title {
  margin: 0 0 16px;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-color);
}

.task-list .task-item {
  position: relative;
}

.task-list .task-item .task-info {
  display: flex;
  gap: 16px;
  color: var(--text-color-secondary);
  font-size: 12px;
}

.task-list .task-item .task-info .task-id {
  font-family: monospace;
}

.task-list .task-item .action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.task-list .task-item .action-buttons .status-btn {
  opacity: 0.8;
}

.task-list .task-item .action-buttons .status-btn:hover {
  opacity: 1;
}

.task-list .task-item .action-buttons .log-btn {
  opacity: 0.8;
}

.task-list .task-item .action-buttons .log-btn:hover {
  opacity: 1;
}

/* 日志弹窗样式 */
.task-log-dialog .van-dialog__message {
  white-space: pre-wrap;
  font-family: 'Fira Code', monospace;
  max-height: 60vh;
  overflow-y: auto;
  padding: 16px;
  background-color: #1e1e1e;
  color: #d4d4d4;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
}

.task-log-dialog .van-dialog__message::-webkit-scrollbar {
  width: 6px;
}

.task-log-dialog .van-dialog__message::-webkit-scrollbar-thumb {
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

.workflow-info {
  margin: 8px 0;
  padding: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 14px;
}

.workflow-info .label {
  color: var(--text-color-secondary);
  margin-right: 8px;
}

.workflow-info .value {
  color: var(--text-color);
  font-weight: 500;
}

/* 状态颜色样式 */
.task-state {
  font-size: 13px;
  margin-left: 8px;
}

.state-running { 
  color: #409eff;  /* 运行中/提交成功-蓝色 */
}
.state-success { 
  color: #67c23a;  /* 成功-绿色 */
}
.state-failed { 
  color: #f56c6c;  /* 失败/需要容错-红色 */
}
.state-paused { 
  color: #e6a23c;  /* 暂停/准备暂停-橙色 */
}
.state-stopped { 
  color: #909399;  /* 停止/准备停止/终止-灰色 */
}
.state-default { 
  color: #606266;  /* 其他状态-深灰色 */
}
</style> 